#include "cxinoticewidget.h"
#include <QDateTime>
#include <QMouseEvent>
#include <QStyle>
#include <QTimer>
#include <ui_CxiNoticeWidget.h>
static int g_clickCount = 0;
static int g_doubleClickInterval = 200;
CxiNoticeWidget::CxiNoticeWidget(const NoticeData& data, QWidget* parent)
	: QWidget(parent),
	  ui(new Ui::CxiNoticeWidget),
	  m_autoCloseTimer(new QTimer(this)),
	  m_clickTimer(new QTimer(this))
{
	ui->setupUi(this);
	setWindowFlags(Qt::Tool | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
	m_data = initData(data);
	//初始化ui
	init();
}
NoticeData CxiNoticeWidget::initData(const NoticeData& inputData)
{
	NoticeData result = inputData;
	// 对未有效设置的字段，填充默认值
	if (result.text.isEmpty())
	{
		result.text = QString();
	}
	if (result.caption.isEmpty())
	{
		result.caption = tr("提示");
	}
	if (result.icon.isNull())
	{
		switch (result.type)
		{
		case NoticeType::Notice:
			result.icon = style()->standardIcon(QStyle::SP_MessageBoxInformation);
			break;
		case NoticeType::Message:
			result.icon = style()->standardIcon(QStyle::SP_MessageBoxInformation);
			break;
		case NoticeType::Remind:
			result.icon = style()->standardIcon(QStyle::SP_MessageBoxWarning);
			break;
		case NoticeType::Warning:
			result.icon = style()->standardIcon(QStyle::SP_MessageBoxCritical);
			break;
		case NoticeType::Confirm:
			result.icon = style()->standardIcon(QStyle::SP_MessageBoxQuestion);
			break;
		case NoticeType::MQ:
			result.icon = style()->standardIcon(QStyle::SP_MessageBoxQuestion);
			break;
		default:
			result.icon = style()->standardIcon(QStyle::SP_MessageBoxInformation);
		}
	}
	if (result.size.isEmpty())
	{
		switch (result.sizeStyle)
		{
		case NoticeSizeStyle::Normal:
			result.size = QSize(300, 100);
			break;
		case NoticeSizeStyle::Large:
			result.size = QSize(400, 150);
			break;
		case NoticeSizeStyle::Larger:
			result.size = QSize(500, 200);
			break;
		default:
			result.size = QSize(300, 100);
		}
	}
	if (result.font.family().isEmpty())
	{
		result.font = QFont("微软雅黑", 10);
	}
	if (!result.backColor.isValid())
	{
		switch (result.type)
		{
		case NoticeType::Notice:
			result.backColor = QColor(230, 238, 245);// 浅灰
			break;
		case NoticeType::Message:
			result.backColor = QColor(235, 250, 235);// 浅绿
			break;
		case NoticeType::Remind:
			result.backColor = QColor(255, 250, 230);// 浅黄
			break;
		case NoticeType::Warning:
			result.backColor = QColor(255, 235, 235);// 浅红
			break;
		case NoticeType::Confirm:
			result.backColor = QColor(240, 245, 250);//浅青
			break;
		case NoticeType::MQ:
			result.backColor = QColor(248, 245, 255);//浅紫
			break;
		default:
			result.backColor = QColor(245, 245, 245);// 浅灰
		}
	}
	if (!result.titleColor.isValid())
	{
		result.titleColor = result.backColor;//默认标题颜色和背景颜色一致
	}
	if (!result.isConfirmBox)
	{
		result.isConfirmBox = false;
	}
	if (result.confirmBtnText.isEmpty())
	{
		result.confirmBtnText = tr("确认");
	}
	if (!result.isMQ)
	{
		result.isMQ = false;
	}
	if (result.mqData.isNull())
	{
		result.mqData = QVariant();
	}
	if (!result.confirmCallback)
	{
		result.confirmCallback = []() {};
	}
	// 初始化MQ单击回调
	if (!result.mqClickCallback)
	{
		result.mqClickCallback = [](const QVariant&) {};
	}
	// 初始化MQ双击回调
	if (!result.mqDoubleClickCallback)
	{
		result.mqDoubleClickCallback = [](const QVariant&) {};
	}

	switch (result.type)
	{
	case NoticeType::Notice:
		result.level = NoticeLevel::Level1;
		break;
	case NoticeType::Message:
		result.level = NoticeLevel::Level1;
		break;
	case NoticeType::Remind:
		result.level = NoticeLevel::Level2;
		break;
	case NoticeType::Warning:
		result.level = NoticeLevel::Level4;
		break;
	case NoticeType::Confirm:
		result.level = NoticeLevel::Level3;
		break;
	case NoticeType::MQ:
		result.level = NoticeLevel::Level2;
		break;
	default:
		result.level = NoticeLevel::Level1;
	}
	return result;
}
void CxiNoticeWidget::init()
{
	//初始化ui显示
	ui->iconLabel->setPixmap(m_data.icon.pixmap(64, 64));
	ui->captionLabel->setText(m_data.caption);
	ui->textLabel->setText(m_data.text);

	// 处理确认框
	if (m_data.isConfirmBox)
	{
		ui->confirmButton->setText(m_data.confirmBtnText);
		ui->confirmButton->show();
	}
	else
	{
		ui->confirmButton->hide();
	}
	//设置标题，文本颜色字体等
	ui->captionLabel->setFont(m_data.font);
	QFont captionFont = ui->captionLabel->font();// 获取当前标题字体
	captionFont.setBold(true);                   // 设置粗体
	ui->captionLabel->setFont(captionFont);      // 应用粗体字体
	ui->textLabel->setFont(m_data.font);
	// 背景颜色
	QPalette palette = this->palette();
	palette.setColor(QPalette::Window, m_data.backColor);
	this->setPalette(palette);
	this->setAutoFillBackground(true);
	//标题背景颜色
	QPalette titlePalette = ui->widget_2->palette();
	titlePalette.setColor(QPalette::Window, m_data.titleColor);
	ui->widget_2->setPalette(titlePalette);
	ui->widget_2->setAutoFillBackground(true);
	//设置图标
	ui->iconLabel->setPixmap(m_data.icon.pixmap(50, 50));
	//初始化时间
	m_createTimestamp = QDateTime::currentDateTime().toMSecsSinceEpoch();
	ui->timeLabel->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
	//初始化定时器
	if (m_data.autoPopDelay >= 0)
	{
		m_autoCloseTimer->setInterval(m_data.autoPopDelay);
		m_autoCloseTimer->setSingleShot(true);
		connect(m_autoCloseTimer, &QTimer::timeout, this, &CxiNoticeWidget::onAutoCloseTimeout);
		//m_autoCloseTimer->start();
	}
	//初始化mq消息的鼠标点击时间间隔
	if (m_data.isMQ)
	{
		// 配置单击判断定时器：延迟时间为系统双击间隔，单次触发
		m_clickTimer->setInterval(g_doubleClickInterval);
		m_clickTimer->setSingleShot(true);
		connect(m_clickTimer, &QTimer::timeout, this, [this]() {
			// 定时器超时仍未收到第二次点击，视为单击
			if (g_clickCount == 1)
			{
				emit mqClicked(m_data.mqData);
			}
			g_clickCount = 0;// 重置计数
		});
	}
	// MQ消息设置手型光标
	if (m_data.isMQ)
	{
		setCursor(QCursor(Qt::PointingHandCursor));
	}
	//设置尺寸
	resize(m_data.size);
	//连接确定和关闭按钮点击信号
	connect(ui->closeButton, &QPushButton::clicked, this, &CxiNoticeWidget::onCloseBtnClicked);
	connect(ui->confirmButton, &QPushButton::clicked, this, &CxiNoticeWidget::onConfirmBtnClicked);
}
CxiNoticeWidget::~CxiNoticeWidget()
{
	delete ui;
}
void CxiNoticeWidget::stopAutoCloseTimer()
{
	if (m_autoCloseTimer->isActive())
	{
		m_autoCloseTimer->stop();
	}
}

void CxiNoticeWidget::restartAutoCloseTimer()
{
	if (m_data.autoPopDelay > 0 && !m_autoCloseTimer->isActive())
	{
		m_autoCloseTimer->start(m_data.autoPopDelay);
	}
}
void CxiNoticeWidget::onAutoCloseTimeout()
{
	// 自动关闭时通知私有类移除
	emit needRemove(this);
}

void CxiNoticeWidget::onCloseBtnClicked()
{
	// 手动点击关闭按钮时通知私有类移除
	emit needRemove(this);
}
void CxiNoticeWidget::onConfirmBtnClicked()
{
	emit confirmClicked();
	emit needRemove(this);
}
// 鼠标按下事件
void CxiNoticeWidget::mousePressEvent(QMouseEvent* event)
{
	if (event->button() != Qt::LeftButton || !m_data.isMQ)
	{
		QWidget::mousePressEvent(event);
		return;
	}
	g_clickCount++;// 计数+1
	m_lastClickTime = QDateTime::currentDateTime().toMSecsSinceEpoch();
	QWidget::mousePressEvent(event);
}

// 添加鼠标释放事件，处理单击逻辑
void CxiNoticeWidget::mouseReleaseEvent(QMouseEvent* event)
{
	if (event->button() != Qt::LeftButton || !m_data.isMQ)
	{
		QWidget::mouseReleaseEvent(event);
		return;
	}
	// 如果是第一次点击，启动定时器等待可能的第二次点击
	if (g_clickCount == 1)
	{
		m_clickTimer->start();// 启动定时器，延迟判断
	}
	// 如果是第二次点击（双击），停止定时器，不触发单击
	else if (g_clickCount >= 2)
	{
		m_clickTimer->stop();
		g_clickCount = 0;
	}
	QWidget::mouseReleaseEvent(event);
}
void CxiNoticeWidget::mouseDoubleClickEvent(QMouseEvent* event)
{
	if (event->button() != Qt::LeftButton || !m_data.isMQ)
	{
		QWidget::mouseDoubleClickEvent(event);
		return;
	}
	m_clickTimer->stop();// 停止单击定时器，避免误触发
	g_clickCount = 0;    // 重置计数
	emit mqDoubleClicked(m_data.mqData);
	emit needRemove(this);
	event->accept();
}
void CxiNoticeWidget::enterEvent(QEvent* event)
{
	Q_UNUSED(event)
	// 鼠标悬浮时停止自动关闭
	stopAutoCloseTimer();
}

void CxiNoticeWidget::leaveEvent(QEvent* event)
{
	Q_UNUSED(event)
	// 鼠标离开时重启自动关闭
	restartAutoCloseTimer();
}
NoticeData CxiNoticeWidget::data() const
{
	return m_data;
}
qint64 CxiNoticeWidget::timestamp() const
{
	return m_createTimestamp;
}
void CxiNoticeWidget::showEvent(QShowEvent* event)
{
	QWidget::showEvent(event);
	restartAutoCloseTimer();
}
void CxiNoticeWidget::hideEvent(QHideEvent* event)
{
	QWidget::hideEvent(event);
	stopAutoCloseTimer();
}
NoticeData CxiNoticeWidget::getData() const
{
	return m_data;
}
